package com.ncmmall.application.business.distribution;

import com.ncmmall.domain.business.distribution.DistributionGoods;
import com.ncmmall.domain.business.distribution.DistributionGoodsAssign;
import com.ncmmall.domain.business.distribution.DistributionGoodsAssignRepository;
import com.ncmmall.domain.business.distribution.DistributionGoodsLevel;
import com.ncmmall.domain.business.distribution.DistributionGoodsLevelRepository;
import com.ncmmall.domain.business.distribution.DistributionGoodsRepository;
import com.ncmmall.domain.business.distribution.Distributor;
import com.ncmmall.domain.business.distribution.DistributorLevel;
import com.ncmmall.domain.business.distribution.QDistributionGoodsAssign;
import com.ncmmall.domain.business.distribution.QDistributionGoodsLevel;
import com.ncmmall.domain.business.distribution.QDistributor;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DistributionGoodsApplication {

    @Autowired
    private DistributionGoodsRepository distributionGoodsRepository;

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private DistributionGoodsLevelRepository distributionGoodsLevelRepository;

    @Autowired
    private DistributionGoodsAssignRepository distributionGoodsAssignRepository;

    public void remove(DistributionGoods distributionGoods) {
        if (queryChannelService.selectCount("select count(*) from distribution_goods where merchant_id = :mid and goods_id = :gid", ImmutableMap.of("mid", distributionGoods.getMerchant().getId(), "gid", distributionGoods.getGoods().getId())) >= 1) {
            distributionGoodsLevelRepository.delete(queryChannelService.findAll(QDistributionGoodsLevel.distributionGoodsLevel.distributionGoods.eq(distributionGoods), DistributionGoodsLevel.class));
            distributionGoodsAssignRepository.delete(queryChannelService.findAll(QDistributionGoodsAssign.distributionGoodsAssign.distributionGoods.eq(distributionGoods), DistributionGoodsAssign.class));
            distributionGoodsRepository.delete(distributionGoods);
        } else {
            distributionGoods.setStatus(3);
            distributionGoodsRepository.save(distributionGoods);
        }
    }

    public void removes(List<DistributionGoods> distributionGoodsList) {
        for (DistributionGoods distributionGoods : distributionGoodsList) {
            remove(distributionGoods);
        }
    }

    public void create(DistributionGoods params) {

        List<Long> ids = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(params.getGoodsIds()).stream().map(Long::valueOf).collect(Collectors.toList());
        List<Goods> goodsList = queryChannelService.findAll(QGoods.goods.id.in(ids), Goods.class);

        List<DistributorLevel> distributorLevels = queryChannelService.findAll("select d from DistributorLevel d", DistributorLevel.class);

        List<Distributor> distributorList;
        if (params.getDistributorScope() == 2) {
            ids = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(params.getDistributorIds()).stream().map(Long::valueOf).collect(Collectors.toList());
            distributorList = queryChannelService.findAll(QDistributor.distributor.id.in(ids), Distributor.class);
        } else {
            distributorList = queryChannelService.findAll("select d from Distributor d", Distributor.class);
        }

        for (Goods goods : goodsList) {

            int count = queryChannelService.selectCount("select count(*) from distribution_goods where goods_id = :gid and distributorScope = 1 and status != 3", ImmutableMap.of("gid", goods.getId()));
            if (count > 0) {
                continue;
            }

            distributorList.removeIf(distributor -> queryChannelService.selectCount("select count(*) from distribution_goods_assign ga left join distribution_goods dg on ga.distributionGoods = dg.id where dg.goods_id = :gid and ga.distributor_id = :did and dg.status != 3", ImmutableMap.of("gid", goods.getId(), "did", distributor.getId())) > 0);
            if (distributorList.size() == 0) {
                continue;
            }

            DistributionGoods distributionGoods = new DistributionGoods();
            distributionGoods.setMerchant(goods.getMerchant());
            distributionGoods.setGoods(goods);
            distributionGoods.setDistributorScope(params.getDistributorScope());
            distributionGoods.setCreateTime(new Timestamp(System.currentTimeMillis()));
            distributionGoods.setGuaranteeScale(params.getGuaranteeScale());
            distributionGoods.setStatus(1);
            distributionGoodsRepository.save(distributionGoods);

            //保存当前每个分销商等级的分销比例
            for (DistributorLevel level : distributorLevels) {
                DistributionGoodsLevel distributionGoodsLevel = new DistributionGoodsLevel();
                distributionGoodsLevel.setDistributionGoods(distributionGoods);
                distributionGoodsLevel.setLevel(level.getLevel());
                distributionGoodsLevel.setFirstLevelScale(level.getFirstLevelScale() == null ? 0 : level.getFirstLevelScale());
                distributionGoodsLevel.setSecondLevelScale(level.getSecondLevelScale() == null ? 0 : level.getSecondLevelScale());
                distributionGoodsLevelRepository.save(distributionGoodsLevel);
            }


            for (Distributor distributor : distributorList) {
                DistributionGoodsAssign distributionGoodsAssign = new DistributionGoodsAssign();
                distributionGoodsAssign.setDistributionGoods(distributionGoods);
                distributionGoodsAssign.setDistributor(distributor);
                distributionGoodsAssign.setThirdChannel(goods.getGoodsChannel().getId());
                distributionGoodsAssign.setSecondChannel(goods.getGoodsChannel().getParent().getId());
                distributionGoodsAssign.setFirstChannel(goods.getGoodsChannel().getParent().getParent().getId());
                distributionGoodsAssignRepository.save(distributionGoodsAssign);
            }
        }
    }

    public void disable(DistributionGoods distributionGoods) {
        distributionGoods.setStatus(2);
        distributionGoodsRepository.save(distributionGoods);
    }

    public void enable(DistributionGoods distributionGoods) {
        distributionGoods.setStatus(1);
        distributionGoodsRepository.save(distributionGoods);
    }

    /**
     * 编辑排序值
     */
    public void modifyRank(DistributionGoods distributionGoods) {
        DistributionGoods goods = queryChannelService.findOne(DistributionGoods.class, distributionGoods.getId());
        goods.setRank(distributionGoods.getRank());
        distributionGoodsRepository.save(goods);
    }
}
